﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.IO;
using System.Text;
using System.Xml;
using BLL;
using IYASAKAReport;
using Model;
using UtilityHelper;

namespace IYAKASAPortal.PrintAll
{
    public partial class PrintAuto : System.Web.UI.Page
    {
        private static SqlConnection conn { get; set; }

       // private AutoPrintHelper m_autoPrintHelper = null;
        private static string strMessage { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                form2.Target = "_blank";
            }
            if (Request["LineNum"] != null && Request["LineNum"].ToString() != "")
            {
                txtLineNum.Text = Request["LineNum"].ToString();
            }
        }
        //开始打印
        protected void btnStart_Click(object sender, EventArgs e)
        {

            try
            {
                string strLineNum = txtLineNum.Text.Trim();
                if (string.IsNullOrEmpty(strLineNum))
                {
                    gfLibrary.gfAjaxJs.SetAlertMsg(this.UpdatePanel1, "请输入检测线号！");
                    return;
                }

                if (!gfLibrary.gfValidate.Is_Integer(strLineNum))
                {
                    gfLibrary.gfAjaxJs.SetAlertMsg(this.UpdatePanel1, "检测线号必须为整数！");
                    return;
                }


               // (AutoPrintHelper.GetInstance()).GeneratePrintList(Convert.ToInt32(strLineNum));

                Timer1.Enabled = true;
                txtLineNum.Enabled = false;
                btnStart.CssClass = "btnStartDisabled";
                btnStart.Enabled = false;

                if (conn != null)
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        strMessage = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " :数据库已连接!";
                    }
                    else
                    {
                        conn.Open();
                        strMessage = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " :数据库已经连接成功!";

                    }
                }
                else
                {
                    conn = new SqlConnection(Config.AppConfig.g_strConnectionStringSqlClient);
                    conn.Open();
                    strMessage = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " :数据库已连接!";
                }
                lstMessage.Items.Insert(0, new ListItem() { Text = strMessage, Value = DateTime.Now.ToString() });



            }
            catch (Exception ex)
            {
                strMessage = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " :数据库连接出错，错误信息为：" + ex.Message;
                lstMessage.Items.Insert(0, new ListItem() { Text = strMessage, Value = DateTime.Now.ToString() });
                btnStart.CssClass = "btnStart";
                btnStart.Enabled = true;
            }
        }
        //暂停打印
        protected void btnStop_Click(object sender, EventArgs e)
        {
            Timer1.Enabled = false;
            //drpPrint.Enabled = true;
            txtLineNum.Enabled = true;
            strMessage = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " :自动打印已停止.";
            lstMessage.Items.Insert(0, new ListItem() { Text = strMessage, Value = DateTime.Now.ToString() });
            btnStart.CssClass = "btnStart";
            btnStart.Enabled = true;
            (AutoPrintQue.GetInstance()).Clear_AutoPrintQue();
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                int printId = (AutoPrintQue.GetInstance()).Get_Queue(int.Parse(txtLineNum.Text.Trim()));
                if (printId != 0)
                {
                    lstMessage.Items.Insert(0, new ListItem() { Text = "Get Instance===>" + printId, Value = DateTime.Now.ToString() });
                }
                if (printId > 0)
                {
                    lstMessage.Items.Insert(0, new ListItem() { Text = "Open Print Page===>Qualified:", Value = DateTime.Now.ToString() });
                    RESULT_VEHICLE_INFO_BLL bll = new RESULT_VEHICLE_INFO_BLL();
                    RESULT_VEHICLE_INFO[] entitys = bll.GetModelList("ID = "+printId);
                    if (entitys.Length > 0)
                    {
                        bool IsMTC = IYAKASAPortal.Statistics.StaInfoTools.GetIsMTC(entitys[0].CLZLDH);
                        string strContent = string.Empty;
                        if (entitys[0].JYXM == "F1,")
                        {
                            return;
                        }
                        if (IsMTC)  
                        {
                            strContent = "window.open('" + string.Format("PrintAuto_AJMotor.aspx?Key={0}", printId) + "');";
                        }
                        else
                        {
                            strContent = "window.open('" + string.Format("PrintAuto_AJYQ.aspx?Key={0}", printId) + "');";
                        }

                        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "uuu", strContent, true);
                    }
                }

                int printKey = (AutoPrintQue.GetInstance()).Get_U_Queue(int.Parse(txtLineNum.Text.Trim()));
                if (printKey != 0)
                {
                    lstMessage.Items.Insert(0, new ListItem() { Text = "Get Instance===>UnQualified:" + printKey, Value = DateTime.Now.ToString() });
                }
                if (printKey > 0)
                {
                    RESULT_VEHICLE_INFO_BLL bll = new RESULT_VEHICLE_INFO_BLL();
                    RESULT_VEHICLE_INFO[] entitys = bll.GetModelList("ID = " + printKey);
                    bool IsMTC = IYAKASAPortal.Statistics.StaInfoTools.GetIsMTC(entitys[0].CLZLDH);
                    bool succ = UploadResult(printKey);
                    string strUploadMark = "1";
                    if (!succ)
                    {
                        strUploadMark = "2";
                    }
                    lstMessage.Items.Insert(0, new ListItem() { Text = "Open Print Page", Value = DateTime.Now.ToString() });
                    if (!IsMTC)
                    {                       
                        string strURL = string.Format("PrintPage.aspx?Printer=DefualtPrinter&ID={0}&UploadMark={1}&PrintLine={2}", printKey, strUploadMark, txtLineNum.Text.Trim());
                        gfLibrary.gfAjaxJs.OpenNewUrl(UpdatePanel1, strURL);
                    }
                    else
                    {
                        string strContent = "window.open('" + string.Format("PrintAuto_AJMotor.aspx?Key={0}", printKey) + "');";
                        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "uuu", strContent, true);
                    }
                }
            }
            catch (Exception ex)
            {
                strMessage = DateTime.Now.ToString() + " :自动打印出错,请重新打开自动打印页面" + ex.Message;
                lstMessage.Items.Insert(0, new ListItem() { Text = strMessage, Value = DateTime.Now.ToString() });
                btnStop_Click(sender, e);
                strMessage = DateTime.Now.ToString() + " :自动打印出错,暂停自动打印" + ex.Message;
                btnStart_Click(sender, e);
                strMessage = DateTime.Now.ToString() + " :重新开始打印." + ex.Message;
            }
        }

        private bool UploadResult(int id)
        {
            try
            {
                string strEmployee = string.Empty;
                string strJCLSH = string.Empty;
                Services.UploadNetInfos uploadNetInfos = new Services.UploadNetInfos();
                RESULT_VEHICLE_INFO_BLL bll = new RESULT_VEHICLE_INFO_BLL();
                var info = bll.GetModelList("ID = '" + id.ToString() + "'");
                if (info.Length > 0)
                {
                    strJCLSH = info[0].JCLSH;
                }

                EMPLOYEE_USER_BLL employeeBll = new EMPLOYEE_USER_BLL();
                var employeeInfo = employeeBll.GetModelList("LICENSE_NAME LIKE '%08,%'");
                if (employeeInfo.Length > 0)
                {
                    strEmployee = employeeInfo[0].EMPLOYEE_NAME;
                }

                return uploadNetInfos.UploadNetInformation(strJCLSH, strEmployee);
            }
            catch (Exception ex)
            {
 
            }
            return false;

        }



        //根据条件查询并打印报表
        private void PrintData(string Strsql, string JCLX)
        {
            if (conn == null)
            {
                new SqlConnection(Config.AppConfig.g_strConnectionStringSqlClient);
                conn.Open();
                strMessage = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " :数据库重新连接成功";
            }
            int strLineNum = int.Parse(txtLineNum.Text.Trim());
            string strSql = "select top 1 * from RESULT_VEHICLE_INFO where IsPrint=0 and JCXH=" + strLineNum + " and  JCLSH like '" + JCLX + "' and " + Strsql + "";
            SqlCommand cmd;
            SqlDataAdapter da = new SqlDataAdapter(strSql, conn);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count == 0)
            {
                return;
            }
            else
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string strJCLSH = dt.Rows[i][4].ToString();
                    string strID = dt.Rows[i][0].ToString();

                    if (JCLX == "A_%")
                    {
                        if (dt.Rows[i][8].ToString() == "2")
                        {
                            gfLibrary.gfAjaxJs.OpenNewUrl(this.UpdatePanel1, "PrintPage.aspx?JCLSH=" + strJCLSH + "&Printer=DefualtPrinter&ID=" + strID);
                        }
                        else if (dt.Rows[i][8].ToString() == "1")
                        {
                            AutoPrintAJ(strID);
                        }
                    }

                    strSql = "update RESULT_VEHICLE_INFO set IsPrint=1 where ID=" + strID + "";
                    cmd = new SqlCommand(strSql, conn);
                    cmd.ExecuteNonQuery();
                    strMessage = DateTime.Now.ToString() + " :" + strJCLSH + "打印报表完成!";
                }

            }
            lstMessage.Items.Insert(0, new ListItem()
            {
                Text = strMessage,
                Value = DateTime.Now.ToString()
            });

        }

        private void AutoPrintAJ(string strKey)
        {
            try
            {
                Thread t = new Thread(() =>
                {
                    string strContent = "window.open('" + string.Format("PrintAuto_AJ.aspx?Key={0}", strKey) + "');";
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "uuu", strContent, true);
                }
                );
                t.Start();
            }
            catch (Exception ex)
            {
                #region 日志记录
                LogHelper logHelper = LogHelper.GetSingleLogHelper();

                string strCategory = LogHelper.LogType.Error.ToString();
                LOG_INFO logInfo = new LOG_INFO();
                logInfo.Category = strCategory;
                logInfo.JCLSH = "";
                logInfo.HostName = System.Net.Dns.GetHostName();
                logInfo.IPAddress = logHelper.GetIPAddress(logInfo.HostName);
                logInfo.LogTime = DateTime.Now;
                logInfo.Log_Infor = ex.Message;
                logInfo.OpName = "admin";
                logInfo.Name = logHelper.GetLogName(LogHelper.LogType.Error);
                logInfo.FunName = "PrintAuto.aspx.cs -> AutoPrintAJ";

                logHelper.WriteLog(logInfo);
                #endregion
                gfLibrary.gfAjaxJs.SetAlertMsg(this.UpdatePanel1, ex.Message);
            }
        }

        private void AutoPrintZJ(string strKey)
        {
            ReportDocument docZJ = new ReportDocument();
            string strPathZJ = Server.MapPath("~/rpt/CrystalReportZJBGD.rpt");
            SetCRDataSource setData = new SetCRDataSource();
            docZJ = setData.BindZJReportEx(strKey, strPathZJ, false);
            docZJ.PrintToPrinter(1, false, 0, 0);

            ReportDocument docZJRG = new ReportDocument();
            string strPathRG = Server.MapPath("~/rpt/CrystalReportZJRG.rpt");
            docZJRG = setData.BindZJRGReportEx(strKey, strPathRG, false);
            docZJRG.PrintToPrinter(1, false, 0, 0);

            ReportDocument docZJYQ = new ReportDocument();
            string strPathYQ = Server.MapPath("~/rpt/CrystalReportZJYQ.rpt");
            docZJYQ = setData.BindZJYQReportEx(strKey, strPathYQ, false);
            docZJYQ.PrintToPrinter(1, false, 0, 0);
        }

        protected string ZPDSQLstr(string str)
        {
            string AJ = "(";
            string[] zpd = PrintConfig.SelectValue(str).Split(new char[] { ',' });
            for (int i = 0; i < zpd.Length; i++)
            {
                if (i == 0 && zpd[i] != "")
                    AJ += "Z_PD=" + zpd[i] + "";
                if (i == 1 && zpd[i] != "")
                    AJ += " or Z_PD=" + zpd[i] + "";
                if (i == 2 && zpd[i] != "")
                    AJ += " or Z_PD=" + zpd[i] + "";
                if (i == 3 && zpd[i] != "")
                    AJ += " or Z_PD=" + zpd[i] + "";
            }
            AJ += ")";
            return AJ;
        }
        ////安检自动打印
        protected void PrintAJ()
        {
            string AJ = "";
            if (PrintConfig.SelectValue("AJ_ZPDZT") == "1" && PrintConfig.SelectValue("AJ_SHZT") == "1")
            {
                AJ = this.ZPDSQLstr("AJ_ZPD");
                AJ += " and ";
                if (PrintConfig.SelectValue("AJ_SH") == "1")
                    AJ += " IsAudit=1 ";
                else if (PrintConfig.SelectValue("AJ_SH") == "0")
                    AJ += " IsAudit=0 ";
                PrintData(AJ, "A_%");
            }
            if (PrintConfig.SelectValue("AJ_ZPDZT") == "1" && PrintConfig.SelectValue("AJ_SHZT") == "0")
            {
                AJ = this.ZPDSQLstr("AJ_ZPD");//aj -> Z_PD =1 
                PrintData(AJ, "A_%");
            }
            if (PrintConfig.SelectValue("AJ_ZPDZT") == "0" && PrintConfig.SelectValue("AJ_SHZT") == "1")
            {
                if (PrintConfig.SelectValue("AJ_SH") == "1")
                    AJ += "IsAudit=1";
                else if (PrintConfig.SelectValue("AJ_SH") == "0")
                    AJ += "IsAudit=0";
                PrintData(AJ, "A_%");
            }
            if (PrintConfig.SelectValue("AJ_ZPDZT") == "0" && PrintConfig.SelectValue("AJ_SHZT") == "0")
            {

                PrintData("0=0", "A_%");
            }

        }
        //综检自动打印
        protected void PrintZJ()
        {
            string ZJ = "";
            if (PrintConfig.SelectValue("ZJ_ZPDZT") == "1" && PrintConfig.SelectValue("ZJ_SHZT") == "1")
            {
                ZJ = this.ZPDSQLstr("ZJ_ZPD");
                ZJ += " and ";
                if (PrintConfig.SelectValue("ZJ_SH") == "1")
                    ZJ += " IsAudit=1 ";
                else if (PrintConfig.SelectValue("ZJ_SH") == "0")
                    ZJ += " IsAudit=0 ";
                PrintData(ZJ, "Z_%");
            }
            if (PrintConfig.SelectValue("ZJ_ZPDZT") == "1" && PrintConfig.SelectValue("ZJ_SHZT") == "0")
            {
                ZJ = this.ZPDSQLstr("ZJ_ZPD");
                PrintData(ZJ, "Z_%");
            }
            if (PrintConfig.SelectValue("ZJ_ZPDZT") == "0" && PrintConfig.SelectValue("ZJ_SHZT") == "1")
            {
                if (PrintConfig.SelectValue("ZJ_SH") == "1")
                    ZJ += "IsAudit=1";
                else if (PrintConfig.SelectValue("ZJ_SH") == "0")
                    ZJ += "IsAudit=0";
                PrintData(ZJ, "Z_%");
            }
            if (PrintConfig.SelectValue("ZJ_ZPDZT") == "0" && PrintConfig.SelectValue("ZJ_SHZT") == "0")
            {
                PrintData("0=0", "Z_%");
            }
        }

        private void WriteLog(string logMsg)
        {
            try
            {
                #region 日志记录
                LogHelper logHelper = LogHelper.GetSingleLogHelper();
                string strCategory = LogHelper.LogType.Normal.ToString();
                LOG_INFO logInfo = new LOG_INFO();
                logInfo.Category = strCategory;
                logInfo.HostName = System.Net.Dns.GetHostName();
                logInfo.IPAddress = System.Net.Dns.GetHostAddresses(logInfo.HostName).GetValue(1).ToString();
                logInfo.LogTime = DateTime.Now;

                logInfo.JCLSH = string.Empty;
                logInfo.Log_Infor = logMsg;
                logInfo.OpName = string.Empty;
                logInfo.Name = logHelper.GetLogName(LogHelper.LogType.Normal);
                logInfo.FunName = "PrintAuto.aspx.cs::PrintData";

                logHelper.WriteLog(logInfo);
                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}